/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.client.form;

import java.util.Collection;
import java.util.List;

import org.jb.sharedbills.client.gin.EventId;
import org.jb.sharedbills.client.resources.Resources;
import org.jb.sharedbills.client.stores.EventLoader;
import org.jb.sharedbills.shared.model.Event;
import org.jb.sharedbills.shared.model.Member;
import org.jb.sharedbills.shared.model.Refund;
import org.jb.sharedbills.shared.model.logic.RefundBuilder;

import com.extjs.gxt.charts.client.Chart;
import com.extjs.gxt.charts.client.model.ChartModel;
import com.extjs.gxt.charts.client.model.Legend;
import com.extjs.gxt.charts.client.model.Legend.Position;
import com.extjs.gxt.charts.client.model.charts.PieChart;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.HtmlContainer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.VBoxLayout;
import com.extjs.gxt.ui.client.widget.layout.VBoxLayoutData;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Anchor;
import com.google.inject.Inject;

public class ActionPanel extends ContentPanel {

	@Inject
	public ActionPanel( EventLoader eventLoader, @EventId String eventId ) {
		this.eventLoader = eventLoader;
		
		setHeaderVisible(true);
		setHeading("Actions");
		setFrame(true);
		setHeight(83);
		setLayout( new VBoxLayout() );
		
		Anchor aprint = new Anchor("Imprimer copier/coller", GWT.getHostPageBaseURL() + "report.jsp?id=" + eventId, "_blank");
		add( aprint, new VBoxLayoutData() );
		
		Anchor a1 = new Anchor("Répartir les remboursements");
		a1.addClickHandler( new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				GWT.runAsync( new ModalRunAsync() {
					@Override
					public void execute() {
						showRefunds();
					}
				});
			}
			
		} );
		Anchor a2 = new Anchor("Statistiques");
		a2.addClickHandler( new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				GWT.runAsync( new ModalRunAsync() {					
					@Override
					public void execute() {
						showChart();
					}
				});
			}
			
		} );
		
		add( a1, new VBoxLayoutData() );
		add( a2, new VBoxLayoutData() );
		
	}
	
	/**
	 * 
	 */
	private void showRefunds() {
		eventLoader.load( new AsyncCallback<Event>() {
			
			@Override
			public void onSuccess(Event result) {
				RefundDialog dlg = new RefundDialog(result.getMembers());
				dlg.show();
			}
			
			@Override
			public void onFailure(Throwable caught) {}
		});
	}
	
	
	/**
	 * 
	 */
	private void showChart() {
		eventLoader.load( new AsyncCallback<Event>() {
			
			@Override
			public void onSuccess(Event result) {
				ChartDialog dlg = new ChartDialog(result);
				dlg.show();
			}
			
			@Override
			public void onFailure(Throwable caught) {}
		});
	}
	
	/**
	 * 
	 * @author jeremie
	 *
	 */
	public static class RefundDialog extends Dialog {
		
		public RefundDialog( Collection<Member> members ) {
			setModal( true );
			
			setLayout( new VBoxLayout() );

			setHeight(300);
			setWidth(300);
			setHideOnButtonClick(true);
			setBodyStyle("padding: 10px");
			
			setHeading("Remboursements");
			
			NumberFormat numberFormat = NumberFormat.getFormat("0.00");
			
			String arrowHtml = AbstractImagePrototype.create(Resources.INSTANCE.arrow_right()).getHTML();
			
			List<Refund> refunds = RefundBuilder.build(members);
			for( Refund refund : refunds ) {
				
				StringBuilder builder = new StringBuilder();
				builder.append( refund.getFrom().getName() );
				builder.append("&nbsp;<i>");
				builder.append( numberFormat.format( refund.getAmount() ) );
				builder.append("</i>&nbsp;&nbsp;");
				builder.append(arrowHtml);
				builder.append("&nbsp;");
				builder.append( refund.getTo().getName() );
				
				HtmlContainer r = new HtmlContainer( builder.toString() );
				add( r );
			}
		}
	}
	
	/**
	 * 
	 * @author jeremie
	 *
	 */
	public static class ChartDialog extends Dialog {
		
		public ChartDialog( Event event ) {
			this.event = event;
			
			setModal( true );
			setLayout( new FitLayout() );
			setHeight( 500 );
			setWidth( 500 );
			setHideOnButtonClick(true);
			setResizable(false);
			setDraggable(false);
			
			setHeading("Statistiques");
			
			final Chart chart = new Chart(GWT.getHostPageBaseURL() + "../gxt/chart/open-flash-chart.swf");  
		    chart.setBorders(true);  
		    chart.setChartModel(getPieChartData());  
		      
		    add(chart);      
		}
		
		private ChartModel getPieChartData() {  
		    ChartModel cm = new ChartModel("Dépenses",  
		        "font-size: 14px; font-family: Verdana; text-align: center;");  
		    cm.setBackgroundColour("#fffff5");  
		    Legend lg = new Legend(Position.RIGHT, true);  
		    lg.setPadding(10);  
		    cm.setLegend(lg);  
		      
		    PieChart pie = new PieChart();  
		    pie.setAlpha(0.5f);  
		    pie.setNoLabels(false);  
		    pie.setGradientFill(true);
		    pie.setTooltip("#label# #val#<br>#percent#");  
		    pie.setColours("#ff0000", "#00aa00", "#0000ff", "#ff9900", "#ff00ff", "#800080", "#808000", "#006060", "#000060");  
		    
		    for( Member m : event.getMembers()) {
		    	if (m.getMaxAmount() > 0)
		    		pie.addSlice( m.getMaxAmount(), m.getName() );
		    }
		    		  
		    cm.addChartConfig(pie);  
		    return cm;  
		  }
		
		final private Event event;
	}
	
	final private EventLoader eventLoader;
}
